/*
 * @Description:
 * @Author: liyuhao
 * @Date: 2022-04-25 17:06:41
 * @LastEditors: liyuhao
 * @LastEditTime: 2022-04-28 16:39:34
 */
import React, {useReducer} from 'react'
import {Button, message, Modal, Upload} from 'antd'
import useBaseFontSize from "@/hooks/useBaseFontSize.ts";

export interface ImportModalProps {
    visible?: boolean
    uploadService?: (file?: any) => Promise<any>
    tempUrl?: string
    dispatch?: (action?: any) => void
}

const _service = () => Promise.resolve()
const accept = ['xls', 'xlsx']

const ImportModal: React.FC<ImportModalProps> = (props) => {
    const {visible, uploadService = _service, tempUrl, dispatch} = props
    const baseFontSize = useBaseFontSize();
    const handleClose = () => {
        dispatch && dispatch({type: 'close'})
    }

    const handleBeforeUpload = (file: any) => {
        const type = file.name.split('.')[file.name.split('.').length - 1]
        if (!accept.includes(type?.toLocaleLowerCase())) {
            message.error(`请上传${accept.join('、')}格式的文件`)
            return false
        }

        return file
    }

    const handleRequest = (options: any) => {
        const {file, onSuccess, onError} = options
        const formData = new FormData()
        formData.append('file', file)
        uploadService(formData)
            .then((res) => onSuccess && onSuccess(res))
            .catch((e) => onError(e))
    }

    return (
        <Modal
            centered={true}
            width={1000 * baseFontSize}
            title="批量导入"
            open={visible}
            destroyOnClose
            footer={null}
            onCancel={handleClose}
            focusTriggerAfterClose={false}
        >
            <div>
                <div className="mb-24">
                    <a href={tempUrl} style={{marginRight: 12}}>
                        模板下载.xlsx
                    </a>
                    <a href={`${import.meta.env.BASE_URL}temps/区域编码.xls`}>
                        区域编码下载.xls
                    </a>
                </div>
                <Upload
                    customRequest={handleRequest}
                    beforeUpload={handleBeforeUpload}
                    maxCount={1}
                >
                    <Button>选择文件</Button>
                </Upload>
            </div>
        </Modal>
    )
}

export default ImportModal

export const useImportModal = () => {
    return useReducer(
        (_: any, action: { type: string; payload?: any }) => {
            switch (action.type) {
                case 'open':
                    return {
                        visible: true,
                        uploadService: action.payload?.uploadService,
                        tempUrl: action.payload?.tempUrl
                    }
                case 'close':
                    return {visible: false}
                default:
                    throw new Error()
            }
        },
        {visible: false}
    )
}
